﻿using ConfExpert.Forms.Base;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using DevTeam;
using DevExpress.XtraGrid.Views.Grid;
using ConfExpert.Utility;
using ConfExpert.Datasets;

namespace ConfExpert.Forms.Depo.Kauf
{
    public partial class ModelhanePastalBM : XForm
    {
        public ModelhanePastalBM()
        {
            InitializeComponent();
        }

        public DataTable BOMLines;
        public DataSet Result;
        private void ModelhanePastalBM_Load(object sender, EventArgs e)
        {
            this.Text = "Modelhane Pastal BM";
            Result = new DataSet();
            BOMLines = new DataTable();
            Result.Tables.Add(BOMLines);

            foreach (string s in "DosyaAdi,OrderName,Dagilim,Model,Aciklama,PLU,Color,Total,A01,A02,A03,A04,A05,A06,A07,A08,A09,A10,A11,A12,A13,A14,A15,Uretici,Artikel".Split(",".ToCharArray()))
                BOMLines.Columns.Add(s, typeof(string));

            gleCustomer.Edit.Assign(RI(Rp.V_Customer));
            gleCustomer.EditValue = 245;

            gridView1.Init("GetModelhanePastalBM", gleCustomer.EditValue.ToInt(), 1);
            gridView1.AddDetailGrid(gridView2, "BMIstekId");
            gridView1.AddDetailGrid(gridView3, "BMIstekId");

            gridView2.AddColumn("isPastalLine", typeof(int), "IIF(SipKes=3,1,0)");
            gridView1.AddColumn("QtyNeeded", typeof(decimal), "Total*OrtBM");
            gridView1.AddColumn("PastalSatırı", typeof(int), "SUM(Child({FK}).isPastalLine)");
            gridView1.YanYanaGetirSagina("OrtBM", "QtyNeeded");
            gridView1.YanYanaGetirSoluna("Color", "Artikel");
            
            gridView1.MakeReadOnly();

            gridView1.MakeColumnInvisible("BMIstekLinesId", "CustomerId", "Dagilim", "PLU", "Scan", "ProductId", "DosyaAdi", "OrderName", "Aciklama2");
            gridView2.MakeColumnInvisible("PastalBMLinesId", "BMIstekPastalId", "BMIstekId", "Total", "UserId", "InsertedOn", "isPastalLine");
            gridView3.MakeColumnInvisible("BMIstekLinesId", "Nr");
            //gridView1.Columns["InsertedOn"].VisibleIndex = 0;


            gridView2.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            gridView2.Columns["SipKes"].ColumnEdit = GetCustomRI("Tür", true, "Sipariş Adedi", "Kesilen Adet", "Pastal");
            gridView2.Columns["SipKes"].Caption = "Tür";

            gridView1.FormatAsNumber(0, "Total", "PastalSatırı");
            gridView1.FormatAsNumber(1, "QtyNeeded");
            gridView1.FormatAsNumber(3, "OrtBM");
            gridView1.AddSummary("Total", "QtyNeeded");
            gridView2.AddSummary();

            gridView3.MakeReadOnly("BM");

            //btnProcess.ItemClick += btnProcess_ItemClick;
            btnSave.ItemClick += btnSave_ItemClick;
            gleCustomer.EditValueChanged += gleCustomer_EditValueChanged;

            splitContainerControl1.AutoSize();
            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
            gridView1_FocusedRowChanged(null, null);

            //gridView1.AddAutoIncrementalPK("PastalBMId");
            //gridView2.AddAutoIncrementalPK("PastalBMLinesId");
            gridView2.AddAutoIncrementalPK("BMIstekPastalId");
            gridView2.DataTable().TableNewRow += PastalBM_TableNewRow;
            gridView2.ShowingEditor += gridView2_ShowingEditor;
            gridView3.ShowingEditor += gridView3_ShowingEditor;
            gridView2.RowStyle += gridView2_RowStyle;

            gridView2.EnableRowDelete();
            gridView2.OptionsView.EnableAppearanceEvenRow = gridView2.OptionsView.EnableAppearanceOddRow = false;
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
            gridView3.BestFitColumns();

            if (!ytk(224))
            {
                gleCustomer.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }

        }

        

        void gridView2_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            /*e.Cancel = !(
                ytk(221) &&
                (gridView2.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle || gridView2.GetFocusedDataRow()["SipKes"].ToInt() == 3) &&
                (gridView2.FocusedColumn.FieldName.StartsWith("A") || gridView2.FocusedColumn.FieldName == "PBoy"));*/
            e.Cancel = !(
                (gridView2.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle || gridView2.GetFocusedDataRow()["SipKes"].ToInt() == 3) &&
                (gridView2.FocusedColumn.FieldName.StartsWith("A") || gridView2.FocusedColumn.FieldName == "PBoy"));
        }
        
        void gridView3_ShowingEditor(object sender, CancelEventArgs e)
        {
            if (gridView3.FocusedRowHandle == 0)
                e.Cancel = true;
            else
                e.Cancel = false;
        }

        void PastalBM_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["SipKes"] = 3;
        }

        int DagilimId = 0;
        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridView1.GetFocusedDataRow() != null)
            {
                /*string Dagilim = gridView1.GetFocusedDataRow()["Dagilim"].ToStr();
                int ix = 0;
                foreach (string col in Dagilim.Split(",".ToCharArray()))
                    if (ix < 15)
                        if (col != string.Empty)
                            gridView2.Columns[string.Format("A{0:00}", ++ix)].Caption = col;

                for (int i = ix + 1; i < 15; i++)
                {
                    string col = string.Format("A{0:00}", i);
                    gridView2.Columns[col].Caption = " ";
                }*/
                try
                {
                    gridView1.CloseEditor();
                    gridView1.BeginUpdate();
                    if (DagilimId != gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "DagilimId").ToInt(-1))
                    {
                        DagilimId = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "DagilimId").ToInt(-1);

                        MyData.DagilimRow r = AppSession.Lookups.Dagilim.FindByDagilimId(DagilimId);
                        if (r != null)
                            for (int i = 1; i < 29; i++)
                            {
                                string fieldName = String.Format("A{0:00}", i);
                                string cap = r[String.Format("A{0:00}", i)].ToString();
                                gridView2.Columns[fieldName].Caption = cap != string.Empty ? cap : " ";
                            }
                    }

                }
                catch (Exception Ex)
                {
                    throw Ex;
                }
                finally
                {
                    gridView1.EndUpdate();
                }

                gridView2.ShowOnlyNonblankColumns();
                gridView2.YanYanaGetirSagina("SipKes", "PBoy", "PKat");
                gridView2.BestFitColumns();
            }
        }

        void gleCustomer_EditValueChanged(object sender, EventArgs e)
        {
            //btnProcess.Enabled = gleCustomer.EditValue.ToInt() > 0;

            gridView1.RefreshDataSource("GetModelhanePastalBM", gleCustomer.EditValue.ToInt(), 1);
            gridView1.BestFitColumns();
            gridView1_FocusedRowChanged(null, null);
        }

        void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (((GridView)sender).GetRowCellValue(e.RowHandle, "SipKes").ToInt() == 1)
                e.Appearance.BackColor = System.Drawing.Color.LightBlue;
            else
                e.Appearance.Combine((e.RowHandle & 1) != 0 ? gridView2.Appearance.EvenRow : gridView2.Appearance.OddRow);
        }

        void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int RowHandle = gridView1.FocusedRowHandle;
            gridView1.EndEditing();
            gridView2.EndEditing();
            gridView3.EndEditing();
            string XmlStr = gridView3.SerializeChanges();
            /*if (gridView2.DataTable().Select("BMIstekPastalId>0").Length > 0)
            {
                DataTable dt11 = gridView2.DataTable().Select("BMIstekPastalId>0").CopyToDataTable();
                gridView2.RefreshDataSource(dt11);
            }*/
            //gridView1.Update("", "PastalBM");
            //gridView2.Update("BMIstekPastalId,BMIstekLinesId,SipKes,PBoy,PKat,A01,A02,A03,A04,A05,A06,A07,A08,A09,A10,A11,A12,A13,A14,A15,A16,A17,A18,A19,A20,A21,A22,A23,A24,A25,A26,A27,A28", "BMIstekPastal");
            gridView2.Update("", "BMIstekPastal");
            gridView1.RefreshDataSource("GetModelhanePastalBM", gleCustomer.EditValue.ToInt(), 1);

            SetPKat();
            //ExecuteNonQuery("UpdBirimMetrajlar", gridView1.DataTable().Select("OrtBM is not null", string.Empty).CopyToDataTable().Serialize());

            gridView1.EndEditing();
            gridView2.EndEditing();
            gridView3.EndEditing();
            /*if (gridView2.DataTable().Select("BMIstekPastalId>0").Length > 0)
            {
                DataTable dt11 = gridView2.DataTable().Select("BMIstekPastalId>0").CopyToDataTable();
                gridView2.RefreshDataSource(dt11);
            }*/
            //gridView1.Update("", "PastalBM");
            gridView2.Update("", "BMIstekPastal");
            
            ExecuteNonQuery("UpdBMIstekLines", XmlStr);
            gridView1.RefreshDataSource("GetModelhanePastalBM", gleCustomer.EditValue.ToInt(), 1);
            
            gridView1.ClearSelection();
            gridView1.FocusedRowHandle = RowHandle;
            gridView1.SelectRow(RowHandle);
            gridView1_FocusedRowChanged(null, null);
            
        }

        int currentPastalBMId;
        private DataTable dtDagilim
        {
            get
            {
                DataRow[] drs = gridView2.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString() + " AND SipKes=3 AND PBoy>0");
                if (drs.Length > 0)
                    return drs.CopyToDataTable();
                else
                    return null;
            }
        }
        private void SetPKat()
        {
            gridView1.EndEditing();
            gridView2.EndEditing();

            for (int rowHandle = 0; rowHandle < gridView1.DataRowCount; rowHandle++)
            {
                currentPastalBMId = gridView1.GetRowCellValue(rowHandle, "BMIstekId").ToInt(-1);

                List<string> tekBilinmeyenli = new List<string>();
                List<string> cokBilinmeyenli = new List<string>();
                bool eksikPastal = false;     //dolu beden için hiç pastal girilmediyse

                if (dtDagilim != null)
                {
                    for (int dagilimIndex = 1; dagilimIndex < 16; dagilimIndex++)
                    {
                        string colName = "A" + dagilimIndex.ToString().PadLeft(2, '0');

                        foreach (DataRow drx in gridView2.DataTable().Select("BMIstekId=" + currentPastalBMId))
                            if (drx[colName].ToInt(-1) == 0)
                                drx[colName] = DBNull.Value;

                        int doluPastalAdedi = dtDagilim.Compute("Count(" + colName + ")", "").ToInt(-1);
                        int d = dtDagilim.Compute("Count(" + colName + ")", string.Empty).ToInt(-1);
                        eksikPastal |= (d > 0 && SiparisAdedi(colName) == 0) || (d == 0 && SiparisAdedi(colName) > 0);

                        if (doluPastalAdedi == 1)
                            tekBilinmeyenli.Add(colName);
                        else if (doluPastalAdedi > 1)
                            cokBilinmeyenli.Add(colName);
                    }

                    foreach (string colName in tekBilinmeyenli)
                    {
                        DataRow drDagilim = dtDagilim.Select(colName + " is not null")[0];
                        int carpan = drDagilim[colName].ToInt(-1);
                        int pkatMevcut = drDagilim["PKat"].ToInt(-1);
                        int pKat = Convert.ToInt32(Math.Ceiling(SiparisAdedi(colName) / (decimal)carpan));

                        if (pKat > pkatMevcut)
                        {
                            int PastalBMLinesId = drDagilim["BMIstekPastalId"].ToInt();
                            gridView2.DataTable().Select("BMIstekPastalId=" + PastalBMLinesId.ToStr())[0]["PKat"] = pKat;
                        }
                    }

                    List<string> duzeltilen = null;
                    do
                    {
                        duzeltilen = new List<string>();

                        foreach (string colName in cokBilinmeyenli)
                        {
                            DataRow[] bilinmeyen = dtDagilim.Select(colName + " is not null and PKat is null");
                            if (bilinmeyen.Length > 1)
                                continue;

                            if (bilinmeyen.Length == 0)
                            {
                                duzeltilen.Add(colName);
                                continue;
                            }


                            DataRow[] bilinen = dtDagilim.Select(colName + " is not null and PKat is not null");

                            int kapsanan = 0;
                            foreach (DataRow drDagilim in bilinen)
                            {
                                int pKat = drDagilim["PKat"].ToInt(-1);
                                int carpan = drDagilim[colName].ToInt(-1);
                                kapsanan += pKat * carpan;
                            }

                            int eklenecek = SiparisAdedi(colName) - kapsanan;

                            if (eklenecek < 0)
                                eklenecek = 0;

                            DataRow drBilinmeyen = bilinmeyen[0];
                            int PastalBMLinesId = drBilinmeyen["BMIstekPastalId"].ToInt(-1);
                            int carpanBilinmeyen = drBilinmeyen[colName].ToInt(-1);

                            gridView2.DataTable().Select("BMIstekPastalId=" + PastalBMLinesId.ToStr())[0]["PKat"] = eklenecek / carpanBilinmeyen;
                            duzeltilen.Add(colName);
                        }

                        foreach (string duzgun in duzeltilen)
                            cokBilinmeyenli.Remove(duzgun);

                    }
                    while (duzeltilen.Count > 0 &&
                        cokBilinmeyenli.Count > 0);

                    eksikPastal |= cokBilinmeyenli.Count > 0;
                }

                if (eksikPastal)
                {
                    DataRow[] drt = gridView1.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString(), string.Empty);
                    if (drt.Length == 1)
                        gridView1.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString(), string.Empty)[0]["OrtBM"] = DBNull.Value;
                }
                else
                {
                    int toplam = 0;
                    DataRow[] drs = gridView2.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString() + " AND SipKes=3 and PKat is not null");
                    for (int dagilimIndex = 1; dagilimIndex < 16; dagilimIndex++)
                    {
                        string colName = "A" + dagilimIndex.ToString().PadLeft(2, '0');
                        foreach (DataRow drDagilim in drs)
                            if (drDagilim[colName].ToInt(-1) > 0)
                                toplam += drDagilim[colName].ToInt(-1) * drDagilim["PKat"].ToInt(-1);
                    }

                    decimal uzunluk = 0;
                    foreach (DataRow dr in drs)
                        uzunluk += decimalParse(dr["PKat"]) * (decimalParse(dr["PBoy"]) + 0.04m);

                    if (toplam > 0 && uzunluk > 0)
                        MetrajEkle(currentPastalBMId, uzunluk / toplam);
                }
            }
        }

        private int SiparisAdedi(string colName)
        {
            if (gridView2.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString() + " AND SipKes=1").Length > 0)
                return gridView2.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString() + " AND SipKes=1")[0][colName].ToInt();
            else
                return 0;
        }

        void MetrajEkle(int PastalBMId, decimal Metraj)
        {
            DataRow[] drs = gridView1.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString(), string.Empty);
            if (drs.Length == 1)
            {
                bool EsitDegil = false;
                if (Math.Round(gridView1.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString(), string.Empty)[0]["OrtBM"].ToDecimal(), 2) != Math.Round(Metraj, 2))
                    EsitDegil = true;

                gridView1.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString(), string.Empty)[0]["OrtBM"] = (float)Metraj;

                if(EsitDegil)
                    ExecuteNonQuery("UpdBirimMetrajlar2", gridView1.DataTable().Select("BMIstekId=" + currentPastalBMId.ToString(), string.Empty)[0]["BMIstekLinesId"].ToInt(), (float)Metraj);
            }
        }

        private void bbiTumIstekler_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (ModelhaneTumIstekler mti = new ModelhaneTumIstekler())
            {
                if (mti.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    
                    gleCustomer.EditValue = mti.SecilenCustomerId;
                    gridView1.RefreshDataSource("GetModelhanePastalBM", gleCustomer.EditValue.ToInt(), 1);
                    Console.WriteLine("Mesaj Alindi: {0}", mti.SecilenCustomerId);
                    gridView1_FocusedRowChanged(null, null);
                }
                
            }
        }
    }
}
